/*
 * SCT.cpp
 *
 *  Created on: Dec 20, 2011
 *      Author: quotrader
 */

#include "SCT.h"

SCT::SCT() {
	this->name = 3;//"Shortest-Completion-Time";

}

void SCT::run(TaskMng *tMng){
	Task *taskList=tMng->tasks;
	int nof= tMng->numTask;
	Task tmpTL[nof];
	int minExeTim=0;
	int maxExeTim=0;
	int minIndex=0;

	// copy task list to temporary place and get biggest period
	for(int i=0; i< nof; i++){
		tmpTL[i]=taskList[i];
		if(maxExeTim < tmpTL[i].executionTime) maxExeTim= tmpTL[i].executionTime;
	}


	// order tasks and put them back to their original place
	for(int i=0; i< nof; i++){
		minExeTim= maxExeTim;
		for(int j=0; j<nof; j++)
			if(minExeTim >= tmpTL[j].executionTime && tmpTL[j].executionTime != -1){
				minExeTim=tmpTL[j].executionTime;
				minIndex= j;
			}
		if(tmpTL[minIndex].executionTime != -1)taskList[i]=tmpTL[minIndex];
		tmpTL[minIndex].executionTime=-1;
	}
	tMng->changed=false;

}

int SCT::rePrioritize(TaskMng *tMng,int sp, int ip){
	Task *taskList=tMng->tasks;
	int nof=tMng->numTask;
	Task tmpTL[nof];
	int minExeTim = 0;
	int maxExeTim = 0;
	int minIndex = 0;
	int newParam=0;
	int hptID=0;

	// copy task list to temporary place and get longest deadline
	for (int i = 0; i < nof; i++) {
		tmpTL[i] = taskList[i];
		if (maxExeTim < tmpTL[i].executionTime and !tmpTL[i].done)
			maxExeTim = tmpTL[i].executionTime;
	}

	// order tasks and put them back to their original place
	for (int i = 0; i < nof; i++) {
		minExeTim = maxExeTim;
		for (int j = 0; j < nof; j++)
			if (minExeTim >= tmpTL[j].executionTime && tmpTL[j].executionTime != -1 && !tmpTL[j].done) {
				minExeTim = tmpTL[j].executionTime;
				minIndex = j;
			}
		if (tmpTL[minIndex].executionTime != -1){
			if(i==0)hptID=tmpTL[minIndex].id;
			newParam=sp + ((tMng->numTask-i) * ip);
			if(pthread_setschedprio(tmpTL[minIndex].taskThread,newParam)!=0)cout<<"I can't modify priority";
		}
		tmpTL[minIndex].executionTime = -1;
	}
	tMng->changed=false;
	return hptID;
}
